package com.yugao.fintech.draper.scheduled.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yugao.fintech.draper.quartz.service.ScheduledJobLogService;
import com.yugao.fintech.draper.scheduled.convert.QuartzJobLogConvert;
import com.yugao.fintech.draper.scheduled.dto.QuartzJobLogDTO;
import com.yugao.fintech.draper.scheduled.dto.QuartzJobLogQuery;
import com.yugao.fintech.draper.scheduled.entity.QuartzJobLog;
import com.yugao.fintech.draper.scheduled.mapper.QuartzJobLogMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 定时任务调度日志表
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QuartzJobLogService implements ScheduledJobLogService {
	private final QuartzJobLogMapper quartzJobLogMapper;

	/**
	 * 分页
	 */
	public IPage<QuartzJobLogDTO> page(QuartzJobLogQuery queryVo) {
		LambdaQueryWrapper<QuartzJobLog> wrapper = Wrappers.<QuartzJobLog>lambdaQuery()
				.eq(StrUtil.isNotBlank(queryVo.getJobName()), QuartzJobLog::getJobName, queryVo.getJobName());
		Page<QuartzJobLog> page =  quartzJobLogMapper.selectPage(Page.of(queryVo.getPageNum(), queryVo.getPageSize()), wrapper);
		return QuartzJobLogConvert.INSTANCE.convertPage(page);
	}

	/**
	 * 获取单条
	 */
	public QuartzJobLogDTO findById(Long id) {
		QuartzJobLog quartzJobLog = quartzJobLogMapper.selectById(id);
		return QuartzJobLogConvert.INSTANCE.convert(quartzJobLog);
	}

	/**
	 * 保存job执行日志
	 * @param jobBeanName jobBeanName
	 * @param jobMessage job日志信息
	 * @param ex 异常信息
	 */
	@Override
	public void addJobLog(String jobBeanName, String jobMessage, String ex) {
		QuartzJobLogDTO quartzJobLogDto = new QuartzJobLogDTO().setJobName(jobBeanName)
			.setJobMessage(jobMessage)
			.setExceptionInfo(ex)
			.setStatus(StrUtil.isBlank(ex) ? "0" : "1");
		quartzJobLogMapper.insert(QuartzJobLogConvert.INSTANCE.convert(quartzJobLogDto));
	}
}